from django.http import JsonResponse, HttpResponseRedirect, HttpResponse
from django.views.decorators.csrf import csrf_exempt
from django.shortcuts import get_object_or_404, render
from django.urls import reverse
from django.utils import timezone
from ..models.grade_schedule import GradeSchedule
from ..models.grade import Grade
from ..models.semester import Semester
from ..forms.grade_schedule_form import GradeScheduleForm
import json
import logging

# 配置日志
logger = logging.getLogger(__name__)


def is_ajax_request(request):
    """检查请求是否为AJAX请求"""
    return request.headers.get('X-Requested-With') == 'XMLHttpRequest'


def format_date(date_obj):
    """格式化日期为YYYY-MM-DD格式"""
    return date_obj.strftime('%Y-%m-%d') if date_obj else None


def get_schedule_event_info(schedule):
    """获取课程安排的事件信息"""
    # 根据is_class_day设置标题和颜色
    day_type_map = {
        0: ('休息日', '#6c757d'),  # 灰色
        1: ('正常上课', '#28a745'),  # 绿色
        2: ('调休', '#ffc107'),  # 黄色
        3: ('课后服务', '#17a2b8'),  # 青色
        4: ('考试', '#fd7e14')   # 橙色
    }
    title, color = day_type_map.get(schedule.is_class_day, ('未知', '#dc3545'))  # 红色
    
    return {
        'id': schedule.id,
        'title': title,
        'start': format_date(schedule.date),
        'backgroundColor': color,
        'borderColor': color
    }


# 列表视图
@csrf_exempt
def grade_schedule_list(request):
    # 优化查询性能
    schedules = GradeSchedule.objects.select_related('grade', 'semester').order_by('date')
    return render(request, 'core/grade_schedule_list.html', {'schedules': schedules})


# 获取年级课程详情
def get_grade_schedule_detail(request, pk):
    try:
        # 优化查询性能
        schedule = GradeSchedule.objects.select_related('grade', 'semester').get(pk=pk)
        data = {
            'id': schedule.id,
            'date': format_date(schedule.date),
            'is_class_day': schedule.is_class_day,
            'grade': schedule.grade.id,
            'semester': schedule.semester.id
        }
        return JsonResponse(data)
    except GradeSchedule.DoesNotExist:
        logger.warning(f'年级课程不存在，ID: {pk}')
        return JsonResponse({'error': '年级课程不存在'}, status=404)
    except Exception as e:
        logger.error(f'获取年级课程详情失败: {str(e)}')
        return JsonResponse({'error': '获取年级课程详情失败'}, status=500)


# 创建视图 - 支持AJAX
@csrf_exempt
def grade_schedule_create(request):
    if request.method == 'POST':
        form = GradeScheduleForm(request.POST)
        if form.is_valid():
            try:
                schedule = form.save()
                logger.info(f'创建年级课程成功，ID: {schedule.id}')
                if is_ajax_request(request):
                    return JsonResponse({
                        'status': 'success',
                        'id': schedule.id,
                        'date': format_date(schedule.date),
                        'is_class_day': schedule.is_class_day
                    })
                return HttpResponseRedirect(reverse('core:grade_schedule_list'))
            except Exception as e:
                logger.error(f'创建年级课程失败: {str(e)}')
                if is_ajax_request(request):
                    return JsonResponse({
                        'status': 'error',
                        'errors': '创建年级课程失败'
                    }, status=500)
        else:
            if is_ajax_request(request):
                return JsonResponse({
                    'status': 'error',
                    'errors': form.errors
                }, status=400)
    else:
        form = GradeScheduleForm()
    return render(request, 'core/grade_schedule_form.html', {'form': form, 'title': '创建年级日程'})


# 更新视图 - 支持AJAX
@csrf_exempt
def grade_schedule_update(request, pk):
    schedule = get_object_or_404(GradeSchedule, pk=pk)
    if request.method == 'POST':
        form = GradeScheduleForm(request.POST, instance=schedule)
        if form.is_valid():
            try:
                schedule = form.save()
                logger.info(f'更新年级课程成功，ID: {schedule.id}')
                if is_ajax_request(request):
                    return JsonResponse({
                        'status': 'success',
                        'id': schedule.id,
                        'date': format_date(schedule.date),
                        'is_class_day': schedule.is_class_day
                    })
                return HttpResponseRedirect(reverse('core:grade_schedule_detail', args=[pk]))
            except Exception as e:
                logger.error(f'更新年级课程失败，ID: {pk}, 错误: {str(e)}')
                if is_ajax_request(request):
                    return JsonResponse({
                        'status': 'error',
                        'errors': '更新年级课程失败'
                    }, status=500)
        else:
            if is_ajax_request(request):
                return JsonResponse({
                    'status': 'error',
                    'errors': form.errors
                }, status=400)
    else:
        form = GradeScheduleForm(instance=schedule)
    return render(request, 'core/grade_schedule_form.html', {'form': form, 'title': '更新年级日程'})


# 删除视图 - 支持AJAX
@csrf_exempt
def grade_schedule_delete(request, pk):
    schedule = get_object_or_404(GradeSchedule, pk=pk)
    if request.method == 'POST':
        try:
            schedule.delete()
            logger.info(f'删除年级课程成功，ID: {pk}')
            if is_ajax_request(request):
                return JsonResponse({'status': 'success'})
            return HttpResponseRedirect(reverse('core:grade_schedule_list'))
        except Exception as e:
            logger.error(f'删除年级课程失败，ID: {pk}, 错误: {str(e)}')
            if is_ajax_request(request):
                return JsonResponse({
                    'status': 'error',
                    'errors': '删除年级课程失败'
                }, status=500)
    return render(request, 'core/grade_schedule_confirm_delete.html', {'schedule': schedule})



def get_grade_schedule_by_gradeid(request, grade_id):
    grade = get_object_or_404(Grade, id=grade_id)
    current_semester = Semester.objects.filter(is_current=True).first()
    if not current_semester:
        logger.warning('当前学期信息未设置')
        return JsonResponse({'success': False, 'message': '当前学期信息未设置'})
    
    # 优化查询性能
    schedules = GradeSchedule.objects.select_related('grade', 'semester').filter(
        grade=grade,
        semester=current_semester
    ).order_by('date')
    
    # 转换为FullCalendar格式
    events = [get_schedule_event_info(schedule) for schedule in schedules]
    
    return JsonResponse(events, safe=False)
        

# 生成月课程安排视图
def generate_month_schedule(request):
    if request.method == 'POST':
        try:
            grade_id = request.POST.get('grade')
            semester_id = request.POST.get('semester')
            year = int(request.POST.get('year'))
            month = int(request.POST.get('month'))
            
            # 调用模型方法生成月课程安排
            count = GradeSchedule.generate_month_schedule(grade_id, semester_id, year, month)
            
            # 设置成功消息
            request.session['success_message'] = f'成功生成{count}天的课程安排'
            logger.info(f'生成月课程安排成功，年级: {grade_id}, 学期: {semester_id}, {year}年{month}月, 共{count}天')
            return HttpResponseRedirect(reverse('core:grade_schedule_list'))
        except Exception as e:
            logger.error(f'生成月课程安排失败: {str(e)}')
            request.session['error_message'] = '生成月课程安排失败，请重试'
            return HttpResponseRedirect(reverse('core:generate_month_schedule'))
    else:
        
        # 获取当前年份和月份
        current_year = timezone.now().year
        current_month = timezone.now().month
        grade = Grade.objects.filter(grade_leader=request.user).first()
        current_semester = Semester.objects.filter(is_current=True).first()
        return render(request, 'core/generate_month_schedule.html', {
            'grade': grade,
            'current_semester': current_semester,
            'current_year': current_year,
            'current_month': current_month
        })
        
